package com.qf.homework.service.impl;

import com.qf.homework.aop.anno.Retry;
import com.qf.homework.common.AppException;
import com.qf.homework.common.RetryException;
import com.qf.homework.entity.User;
import com.qf.homework.mapper.UserMapper;
import com.qf.homework.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author zehan
 * @date 2022/8/19 11:26
 */

@Service
@Scope("prototype")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String account, String password) {

        User user = userMapper.selectByAccount(account);
        if (user==null){
            throw new AppException("301","账号不存在");
        }
        if (user.getPassword().equals(password)){
            return user;
        }
        return null;
    }

    @Override
    @Retry
    @Transactional(rollbackFor = Exception.class)
    public void getMoney(String account, BigDecimal money){

        // 1 账号是否存在
        User user = userMapper.selectByAccount(account);
        if (user == null) {
            throw new AppException("301", "账号不存在");
        }
        // 2 余下额度是否够
        if (user.getMoney().compareTo(money) < 0) {
            throw new AppException("304", "余额不够");
        }
//        Thread.sleep(new Random().nextInt(100));
        // 2.1 获得此时的版本号
        Long version = user.getVersion();
        // 3 更新
        int count = userMapper.updateMoney(account, BigDecimal.ZERO.subtract(money), version);
        if (count == 0) {
            throw new RetryException("505","取钱失败，开始重试");
        }
        System.out.println("取钱成功");

    }


    @Override
    public int addUser(User user) {
        return userMapper.insertSelective(user);
    }
}
